#include "frmmain.h"
#include "myhelper.h"
#include <QDebug>
#include "systemfile.h"

frmMain::frmMain(QObject *parent) :
    QObject(parent)
{
this->Init();
}

frmMain::~frmMain()
{
    this->dataLink->mySql_db.close();
}

void frmMain::Init()
{
    //建立数据库连接
    this->dataLink = new databaseClass();
    if(this->dataLink->mySql_db.open())
    {
        qDebug() <<"==========SERVER START==========";
        qDebug()  <<"数据库连接成功！"<<QDateTime::currentDateTime().toString("dddd");
    }
    else
    {
        qDebug() << "数据库连接失败！"<<dataLink->mySql_db.lastError();
    }
    //建立和远程设备连接的本地服务端
    server=new myTcpServer(this->dataLink,this);
    connect(server,SIGNAL(ClientConnect(int,QString,int)),this,SLOT(ClientConnect(int,QString,int)));
    connect(server,SIGNAL(ClientDisConnect(int,QString,int)),this,SLOT(ClientDisConnect(int,QString,int)));
    connect(server,SIGNAL(ClientReadData(int,QString,int,QByteArray)),this,SLOT(ClientReadData(int,QString,int,QByteArray)));
    bool ok=server->listen(QHostAddress::Any,sysInfo->devPort.toInt());
    if (ok)
    {
        qDebug()<<tr("设备数据端口:%1 监听成功").arg(sysInfo->devPort.toInt());
    }else{
        qDebug()<<tr("设备数据端口:%1 监听失败").arg(sysInfo->devPort.toInt())<<server->errorString();
    }
    initServer();
    initTimer();
}

void frmMain::initServer()
{
    //建立服务端口，等待连接
    this->local_socket = new QTcpServer(this);
    //起动本地监听
   // if(!this->local_socket->listen(QHostAddress::QHostAddress(sysInfo->localIp),sysInfo->localPort.toInt()))
    if(!this->local_socket->listen(QHostAddress::Any,sysInfo->localPort.toInt()))
    {
     qDebug()  <<tr("WEB服务IP:%1 端口:%2 监听失败").arg(sysInfo->localIp).arg(sysInfo->localPort)<< local_socket->errorString()<<"\r\n";
    }else{
     qDebug()  <<tr("WEB服务IP:%1 端口:%2 监听成功").arg(sysInfo->localIp).arg(sysInfo->localPort)<<"\r\n";
    }
    connect(this->local_socket,SIGNAL(newConnection()),this,SLOT(local_socket_newConnect()));
  // qDebug()<<"\r\n";
}


void frmMain::initTimer()
{
    //定时连接数据库
    timer=new QTimer(this);
    connect(timer,SIGNAL(timeout()),this,SLOT(traffer_netdata()));
    timer->start(300000);//5 分钟定时
    startTime=QDateTime::currentDateTime();
}

void frmMain::local_socket_newConnect()
{
    this->client_socket = this->local_socket->nextPendingConnection(); //获取已经建立的连接的子套接字
    connect(this->client_socket,SIGNAL(disconnected()),this->client_socket, SLOT(deleteLater()));
    connect(this->client_socket,SIGNAL(disconnected()),this,SLOT(local_socket_disConnect()));//关闭连接时，发送断开连接信号
    connect(this->client_socket,SIGNAL(readyRead()),this,SLOT(local_socket_recProcess()));
    connect(server,SIGNAL(openDoorSend(QString)),this,SLOT(openDoorReceive(QString)));
    qDebug()<< QString("本地Web接入设备IP:%1端口:%2").arg(this->client_socket->peerAddress().toString()).arg(this->client_socket->peerPort());
}

//本地服务接收数据处理
void frmMain::local_socket_recProcess()
{
    QString str;
    QStringList list;
    QByteArray recByte =  this->client_socket->readAll();
    str=QString(recByte).trimmed();
    qDebug() <<"frmMain::local_socket_recProcess:" << recByte.length()<< str<<"\r\n";
    if(str.indexOf(",")<0)
    {
    return;
    }
    list = str.split(',');
    if(list.count() >= 4)
    {
        QString recieve,flag,dev_sn,dev_door;
        dev_sn=list[0];//设备号
        recieve=list[1];//标志位
        flag=list[2];//标志符
        dev_door=list[3];//开启奶柜号(门禁号)
        //"123456,1,OPEN,1"
        //"123456,2,OPEN,1-2-3"
        if(flag=="OPEN")
        {
            server->OpenDoor(dev_sn,recieve,dev_door,str);
        }
    }
}

void frmMain::local_socket_disConnect()
{
    qDebug()<<tr("%1本地客户端设备:[IP:%2 Port:%3]下线")
                           .arg(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"))
                           .arg(this->client_socket->peerAddress().toString()).arg(this->client_socket->peerPort());
}

void frmMain::openDoorReceive(QString data)
{
    //和本地服务器交互，返回设备返回结果
    QStringList list;
    if(data.indexOf(",")<0)
    {
    return;
    }
    list=data.split(',');
    if(list.count()==4)
    {
        if(this->client_socket->state()== QAbstractSocket::ConnectedState)
        {
            this->client_socket->write(data.toLocal8Bit());
            qDebug()<<"frmMain::openDoorReceive:"<<data;
            data.clear();
        }
    }
}

void frmMain::ClientReadData(int clientID,QString IP,int Port,QByteArray data)
{    
    if (!data.isEmpty())
    {
            qDebug()<<tr("接收数据:%1 来自:[clientID:%2 IP:%3 Port:%4]")
                                      .arg(QString(data)).arg(clientID).arg(IP).arg(Port);
    }
}

void frmMain::ClientConnect(int clientID,QString IP,int Port)
{
    qDebug()<<tr("客户端:[clientID:%1 IP:%2 Port:%3]上线")
                                      .arg(clientID).arg(IP).arg(Port);
}

void frmMain::ClientDisConnect(int clientID,QString IP,int Port)
{
    qDebug()<<tr("客户端:[clientID:%1 IP:%2 Port:%3]下线")
                                      .arg(clientID).arg(IP).arg(Port);
}


void frmMain::traffer_netdata()
{
    QDateTime then=QDateTime::currentDateTime();
    int i =startTime.secsTo(then);
    if(i>18000)
    {
        this->dataLink->mySql_db.open();
        startTime=QDateTime::currentDateTime();
    }else{
        if(this->dataLink->mySql_db.isOpen())
        {
            timer->stop();
            timer->start(900000);
        }else{
            this->dataLink->mySql_db.open();
            timer->stop();
            timer->start(30000);
        }
    }
}

